<template>
  <div class="product-card" @click="handleClick">
    <!-- 图片容器 -->
    <div class="image-wrapper">
      <el-image 
        :src="product.imageUrl?.startsWith('http') ? product.imageUrl : `/api${product.imageUrl}`" 
        class="product-image"
        fit="cover"
        lazy
      >
        <div slot="error" class="image-placeholder">
          <i class="el-icon-picture-outline"></i>
        </div>
      </el-image>
      
      <!-- 标签 -->
      <div class="product-tags">
        <span class="tag new-tag" v-if="product.isNew">新品</span>
        <span class="tag discount-tag" v-if="product.isDiscount==1">特惠</span>
      </div>
      
      <!-- 快捷操作 -->
      <div class="quick-actions">
        <div class="action-btn favorite-btn" 
          :class="{ 'is-active': isFavoritePage || product.isFavorite }"
          @click.stop="handleFavorite">
          <i :class="[isFavoritePage ? 'el-icon-delete' : (product.isFavorite ? 'el-icon-star-on' : 'el-icon-star-off')]"></i>
        </div>
        <div class="action-btn cart-btn" @click.stop="handleAddToCart">
          <i class="el-icon-shopping-cart-2"></i>
        </div>
      </div>
    </div>
    
    <!-- 产品信息 -->
    <div class="product-info">
      <h3 class="product-name">{{ product.name }}</h3>
      
      <!-- 产地信息 -->
      <div class="origin-info" v-if="product.placeOfOrigin">
        <i class="el-icon-location-outline"></i>
        <span>{{ product.placeOfOrigin }}</span>
      </div>
      
      <!-- 价格区域 -->
      <div class="price-area">
        <div class="price-wrapper">
          <span class="current-price">¥{{ product.isDiscount==1 ? product.discountPrice : product.price }}</span>
          <span class="original-price" v-if="product.isDiscount==1">¥{{ product.price }}</span>
        </div>
        <div class="stock-info">
          <span class="stock" :class="{ 'low-stock': product.stock < 10 }">
            剩余 {{ product.stock }}
          </span>
          <span class="sales">已售 {{ product.salesCount }}</span>
        </div>
      </div>
      
      <!-- 购买按钮 -->
      <div class="buy-now-btn" @click.stop="handleAddToCart">
        <span>加入购物车</span>
        <i class="el-icon-arrow-right"></i>
      </div>
    </div>
  </div>
</template>

<script>
import Request from '@/utils/request'

export default {
  name: 'ProductCard',
  props: {
    product: {
      type: Object,
      required: true
    },
    isFavoritePage: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      userInfo: JSON.parse(localStorage.getItem('frontUser') || '{}')
    }
  },
  methods: {
    isLogin() {
      // 检查是否登录
      const userStr = localStorage.getItem('frontUser')
      if (!userStr) {
        this.$message({
          type: 'warning',
          message: '请先登录'
        })
        this.$router.push('/login')
        return false
      }
      return true
    },
    async handleAddToCart() {
      try {
        if(!this.isLogin()){
          return
        }

        const data = {
          userId: this.userInfo.id,
          productId: this.product.id,
          quantity: 1
        }

        const res = await Request.post('/cart', data)
        if (res.code === '0') {
          this.$message({
            type: 'success',
            message: '已添加到购物车'
          })
          this.$emit('add-to-cart', this.product)
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '添加失败'
          })
        }
      } catch (error) {
        console.error('添加到购物车失败:', error)
        this.$message({
          type: 'error',
          message: '添加到购物车失败'
        })
      }
    },

    async handleFavorite() {
      try {
        // 如果是在收藏页面，只触发事件
        if (this.isFavoritePage) {
          this.$emit('toggle-favorite', this.product)
          return
        }

        if(!this.isLogin()){
          return
        }

        const data = {
          userId: this.userInfo.id,
          productId: this.product.id,
          status: this.product.isFavorite ? 1 : 0
        }
        const res = await Request.post('/favorite', data)
        if (res.code === '0') {
          // 使用服务器返回的状态
          this.product.isFavorite = res.data.status === 1
          this.$message({
            type: 'success',
            message: this.product.isFavorite ? '收藏成功' : '已取消收藏'
          })
          // 触发事件并传递最新状态
          this.$emit('toggle-favorite', {
            product: this.product,
            status: res.data.status
          })
          
          // 重新获取收藏状态
          this.getFavoriteStatus()
        } else {
          this.$message({
            type: 'error',
            message: res.msg || '操作失败'
          })
        }
      } catch (error) {
        console.error('收藏操作失败:', error)
        this.$message({
          type: 'error',
          message: '操作失败'
        })
      }
    },

    // 获取收藏状态的方法
    async getFavoriteStatus() {
      if (this.userInfo?.id) {
        try {
          const res = await Request.get(`/favorite/user/${this.userInfo.id}`)
          if (res.code === '0') {
            const favorites = res.data
            this.product.isFavorite = favorites.some(f => f.productId === this.product.id && f.status === 1)
          }
        } catch (error) {
          console.error('获取收藏状态失败:', error)
        }
      }
    },

    handleClick() {
      this.$router.push(`/product/${this.product.id}`)
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.getFavoriteStatus();
    });
  }
}
</script>

<style scoped>
.product-card {
  background-color: white;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  transition: all 0.4s ease;
  cursor: pointer;
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.product-card:hover {
  transform: translateY(-6px);
  box-shadow: 0 16px 32px rgba(255, 152, 0, 0.15);
}

/* 图片容器 */
.image-wrapper {
  position: relative;
  width: 100%;
  padding-bottom: 100%;
  overflow: hidden;
  background: linear-gradient(135deg, #fffef5 0%, #fff8e5 100%);
}

.product-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  transition: transform 0.5s ease;
}

.product-card:hover .product-image {
  transform: scale(1.08);
}

.image-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: #FF7F00;
  font-size: 24px;
  background: linear-gradient(135deg, #fffef5 0%, #fff8e5 100%);
}

/* 产品标签 */
.product-tags {
  position: absolute;
  top: 16px;
  left: 16px;
  display: flex;
  gap: 8px;
  z-index: 2;
}

.tag {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
  letter-spacing: 0.5px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.new-tag {
  background: linear-gradient(135deg, #FF7F00, #FFA500);
  color: white;
}

.discount-tag {
  background: linear-gradient(135deg, #FF5722, #F44336);
  color: white;
}

/* 快捷操作按钮 */
.quick-actions {
  position: absolute;
  top: 16px;
  right: 16px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  z-index: 2;
}

.action-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.action-btn i {
  font-size: 18px;
  color: #666;
}

.action-btn:hover {
  transform: scale(1.1);
}

.favorite-btn.is-active {
  background: linear-gradient(135deg, #FF5722, #F44336);
}

.favorite-btn.is-active i {
  color: white;
}

.cart-btn:hover {
  background: linear-gradient(135deg, #FF7F00, #FFA500);
}

.cart-btn:hover i {
  color: white;
}

/* 产品信息 */
.product-info {
  padding: 20px;
  display: flex;
  flex-direction: column;
  flex: 1;
}

.product-name {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: 600;
  color: #FF7F00;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  min-height: 44px;
}

/* 产地信息 */
.origin-info {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 12px;
}

.origin-info i {
  color: #FF7F00;
  font-size: 14px;
}

.origin-info span {
  font-size: 13px;
  color: #666;
}

/* 价格区域 */
.price-area {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 16px;
  margin-top: auto;
}

.price-wrapper {
  display: flex;
  flex-direction: column;
}

.current-price {
  font-size: 20px;
  font-weight: 700;
  color: #FF5722;
}

.original-price {
  font-size: 13px;
  color: #999;
  text-decoration: line-through;
  margin-top: 2px;
}

.stock-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: 2px;
}

.stock, .sales {
  font-size: 12px;
  color: #666;
}

.low-stock {
  color: #FF5722;
}

/* 购买按钮 */
.buy-now-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  background: linear-gradient(135deg, #FF7F00, #FFA500);
  color: white;
  padding: 12px;
  border-radius: 12px;
  font-weight: 600;
  font-size: 14px;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(255, 127, 0, 0.2);
}

.buy-now-btn:hover {
  background: linear-gradient(135deg, #FF6600, #FF8C00);
  box-shadow: 0 6px 16px rgba(255, 127, 0, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .product-name {
    font-size: 15px;
    min-height: 42px;
  }

  .current-price {
    font-size: 18px;
  }

  .buy-now-btn {
    padding: 10px;
    font-size: 13px;
  }
}

@media (max-width: 576px) {
  .product-tags {
    top: 12px;
    left: 12px;
  }

  .quick-actions {
    top: 12px;
    right: 12px;
  }

  .action-btn {
    width: 32px;
    height: 32px;
  }

  .product-info {
    padding: 16px;
  }
}
</style>
